package com.bj58.analysis.tools.common;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.bj58.analysis.tools.common.bean.GTIDBean;
import com.bj58.analysis.tools.exception.FormatException;

/**
 * @description 对GTID或PGTID进行解析
 * @author tzc
 *
 */
public class GTIDUtils {

	/**
	 * @description 对GTID或PGTID进行解析
	 * @param gtid
	 *            GTID或PGTID字符串
	 * @return 如果gtid格式不对，将返回null
	 * @throws FormatException
	 */
	public static GTIDBean parser(String gtid) throws FormatException {
		GTIDBean bean = null;
		if (StringUtils.isNotBlank(gtid)) {
			if (gtid.length() == 36 && gtid.contains("-")
					&& gtid.indexOf("-") == 8) {
				try {
					Map<String, String> map = new HashMap<String, String>();

					String tmpGtid = gtid.replace("-", "");
					String lenthStr = tmpGtid.substring(0, 2);
					int length = Integer.parseInt(lenthStr, 16);
					String subGtid = tmpGtid.substring(0, length);

					// pagetype解析
					String pagetypeStr = subGtid.charAt(2) + "";
					int pageTypeFlag = Integer.parseInt(pagetypeStr, 16);
					String pageType = getPageType(pageTypeFlag);
					if (StringUtils.isNotBlank(pageType))
						map.put("pageType", pageType);

					// cate解析
					String cateStr = subGtid.substring(3, 8);
					int cate = Integer.parseInt(cateStr, 16);
					map.put("cate", cate + "");

					// area解析
					String areaStr = subGtid.substring(8, 13);
					int area = Integer.parseInt(areaStr, 16);
					map.put("area", area + "");

					bean = (GTIDBean) GetObjectToClassUtils.getObjectByMap(
							GTIDBean.class, map);
				} catch (Exception e) {
					throw new FormatException();
				}
			}
		}
		return bean;
	}

	// 对pagetype进行识别
	private static String getPageType(int pageTypeFlag) {
		String pageType = null;

		switch (pageTypeFlag) {
		case 0:
			pageType = "other";
			break;

		case 1:
			pageType = "home";
			break;

		case 2:
			pageType = "index";
			break;

		case 3:
			pageType = "list";
			break;

		case 4:
			pageType = "detail";
			break;

		case 5:
			pageType = "post";
			break;

		case 6:
			pageType = "special";
			break;

		default:
			break;
		}

		return pageType;
	}

}
